import javax.swing.*;
import java.util.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.table.DefaultTableModel;

public class AddTransaction extends javax.swing.JFrame {

    /** Creates new form AddTransaction */
    public AddTransaction() {
        initComponents();
       getDatabase();
        checkRowCount();
        setDate();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add/Edit Transaction");
        setResizable(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Product Name", "Price", "Quantity", "Subtotal"
            }
        ));
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(3).setResizable(false);

        jLabel1.setText("Transaction Number:");

        jLabel2.setText("000001");

        jLabel3.setText("Customer Name:");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jLabel4.setText("Date:");

        jLabel5.setText("04/21/1991");

        jLabel6.setText("Amount Total:");

        jTextField2.setEditable(false);

        jLabel7.setText("Php");

        jButton1.setText("Ok");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel8.setText("Product Name/Product Number:");

        jTextField3.setToolTipText("");
        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jLabel9.setText("Quantity:");

        jButton2.setText("Add Product");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Remove Selected");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Back");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
                                .addContainerGap())
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel1)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jLabel2))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel4)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jLabel5)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 208, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel8)
                                        .addGap(18, 18, 18)
                                        .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)))
                                .addGap(18, 18, 18)
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2)
                                .addGap(37, 37, 37)))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGap(421, 421, 421)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel6)
                                    .addGap(10, 10, 10)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel7))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addContainerGap()))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel6)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JDialog dbox = new JDialog();
    dbox.setSize(400,250);
    int response = JOptionPane.showConfirmDialog(
                    dbox, "Are you sure you want to finish this transaction?", " ", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (response == JOptionPane.YES_OPTION ) {
        if(typer==0){
        Vector a = new Vector();
        a.add("Transaction No:");
        a.add(jLabel2.getText());
        a.add("Date:");
        a.add(jLabel5.getText());
        a.add("Customer:");
        a.add(jTextField1.getText());
        a.add("");
        a.add("");
        a.add("");
        a.add("");
        a.add("");
        a.add("");
        a.add("Product Name");
        a.add("Price");
        a.add("Quantity");
        a.add("Subtotal");

        for(int i = 0; i <row.size(); i++){
            a.addElement(row.elementAt(i));
        }

        a.add("");
        a.add("");
        a.add("Total Amount:");
        a.add(jTextField2.getText());

        if(jTextField1.getText().length() == 0){
                 JOptionPane.showMessageDialog(null, "Customer Name was left blank. Please Enter Again.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else{
            Vector x = new Vector();
            x.addElement(jTextField1.getText());
            x.addElement(""+sum);
            x.addElement(date);
            addTransaction(x);
            Receipt r = new Receipt();
            r.setAll(a);
            r.show();
            r.dispose();
            this.dispose();
            TransactionsProper y = new TransactionsProper();
            y.setType(type);
            y.show(); 
            dbox.dispose();
        }
       }
       else{
       String a = jLabel5.getText();
       String b = jTextField1.getText();
       String c = jTextField2.getText();
       float d = Float.valueOf(c);
       
       
       updateTransaction(b,a,d);
       dbox.dispose();
       this.dispose();
            TransactionsProper y = new TransactionsProper();
            y.setType(type);
            y.show(); 
            
       }
             } else if (response == JOptionPane.NO_OPTION ) {
                dbox.dispose();
            }        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
             checkRowCount();
        String t = "productNo";
        String s = jTextField3.getText();
        boolean charflag = true;
        boolean charflag1 = true;
        boolean intflag = true;

       for (int j = 0;j < jTextField1.getText().length();j++) {
		if (!(Character.isLetter(jTextField1.getText().charAt(j))) && !(Character.isWhitespace(jTextField1.getText().charAt(j)))) {
                    charflag = false;
		}
        }

        for (int j = 0;j < jTextField3.getText().length();j++) {
		if (Character.isLetter(jTextField3.getText().charAt(j))) {
                    charflag1 = true;
                    t = "name";
		}
        }

        for (int j = 0;j < jTextField4.getText().length();j++) {
		if (!(Character.isDigit(jTextField4.getText().charAt(j)))) {
                    intflag = false;
		}
        }

        if(jTextField1.getText().length() == 0){
                 JOptionPane.showMessageDialog(null, "Customer Name was left blank. Please Enter Again.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else if(jTextField3.getText().length() == 0 && jTextField3.isEnabled() == true){
                 JOptionPane.showMessageDialog(null, "Product Name was left blank. Please Enter Again.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else if(jTextField4.getText().length() == 0 && jTextField4.isEnabled() == true){
                 JOptionPane.showMessageDialog(null, "Quantity was left blank. Please Enter Again.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else if(intflag == false){
                 JOptionPane.showMessageDialog(null, "Quantity contains letters or special characters. Please Enter Again.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else if(charflag == false){
                 JOptionPane.showMessageDialog(null, "Customer name contains letters or special characters. Please Enter Again.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else{
            jButton1.setEnabled(true);
            searchData(t, s);
            checkRowCount();
            back++;
        }      
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    JDialog dbox = new JDialog();
    dbox.setSize(400,250);
    int response = JOptionPane.showConfirmDialog(
                    dbox, "Are you sure you want to remove this product from the transaction?", " ", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (response == JOptionPane.YES_OPTION ) {
        Object z = jTable1.getValueAt(jTable1.getSelectedRow(), 3);
        Object n = jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        Object l = jTable1.getValueAt(jTable1.getSelectedRow(), 2);
        String s = (String)z;
        String m = (String)n;
        int q = Integer.parseInt((String)l);
        searchRemove(m, q);
        float j = Float.valueOf(s);
        sum -= j;
        jTextField2.setText(""+sum);
        int x = jTable1.getSelectedRow();
        int y = x*4;

        for(int i = 0; i < 4; i++){
        row.removeElementAt(y);
        }

        back--;
        clearValues(rowCount);
        rowCount--;
        setValues(row, rowCount);
        checkRowCount();
         dbox.dispose();
        }
            else if (response == JOptionPane.NO_OPTION ) {
                dbox.dispose();
            } 
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
   JDialog dbox = new JDialog();
    dbox.setSize(400,250);
    int response = JOptionPane.showConfirmDialog(
                    dbox, "Are you sure you want to cancel this transaction?", " ", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (response == JOptionPane.YES_OPTION ) {
                 if(back > 0){
            for(int i = 0; i < back; i++){
                Object n = jTable1.getValueAt(i, 0);
                Object l = jTable1.getValueAt(i, 2);
                String m = (String)n;
                int q = Integer.parseInt((String)l);
                searchRemove(m, q);
            }
        }

        if((type == 1 || type == 0)){
            this.dispose();
            dbox.dispose();
            TransactionsProper y = new TransactionsProper();
                y.setType(type);
                y.show();
        }
        else{
            this.dispose();
        }
            } else if (response == JOptionPane.NO_OPTION ) {
                dbox.dispose();
            }
            
            
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField3ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AddTransaction().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
 DB DB = new DB();
   int count = 0;
   int countT = 0;
   int countD = 0;
   int rowCount = 0;
   int type = 0;
   int back = 0;
   float sum = 0;
   String resNo = new String();
   String date = new String();
   String phone = new String();
   Vector row = new Vector();
   Vector del = new Vector();
   Connection conn;
   PreparedStatement pstmt;
   Statement stmt;
   ResultSet rset;
   String query;
   private int index;
   private int typer = 0;
   
   public void setType(int type){
        this.type = type;
   }

  public void checkRowCount(){
      if(rowCount == 0){
          jButton1.setEnabled(false);
      }
  }

   
   public void getDatabase(){

       try {
                DB.connect();
            	conn = DB.getConn();

                System.out.println("Connection Successful!!");

                query = "select count(transactionNo) as 'count' from transaction";
                pstmt = conn.prepareStatement(query);
                rset = pstmt.executeQuery();

                rset.next();
                count = rset.getInt("count");
                count += 1;
                jLabel2.setText(""+count);

                DB.disconnect();
                System.out.println("Disconnected!");
                pstmt.close();



             } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
             }

       }

        public void setDate() {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");

        try {
            date = dateFormat.format(calendar.getTime());
            jLabel5.setText(dateFormat.format(calendar.getTime()));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
       public void setValues(Vector r, int rC){
            Object z[] = {null,null,null,null};
            DefaultTableModel model = (javax.swing.table.DefaultTableModel)jTable1.getModel();
            jTable1.setModel(model);

            if(rowCount > 7){
                int q = rowCount - 7;
                for(int w = 0; w < q; w++){
                    model.addRow(z);
                }
            }

       		int columnNum = 0;
       		for(int i = 1; i <= rC; i++){
			for(columnNum = 0; columnNum < 4; columnNum++){
       		jTable1.setValueAt(r.elementAt(columnNum+(4*(i-1))), i-1, columnNum);}
       		columnNum = 0;}
       }

       public void clearValues(int rowCount){

       		int columnNum = 0;
       		for(int i = 1; i <= rowCount; i++){
			for(columnNum = 0; columnNum < 4; columnNum++){
       		jTable1.setValueAt("", i-1, columnNum);}
       		columnNum = 0;}
       }
       
        public void setData(String type, String s, String si)
      {
          Vector temp = new Vector();
         
            try {
                  DB.connect();
                       conn = DB.getConn();
                       
                       query = "Select product.productNo, product.name, product.price from product where product."+type+" = '"+s+"' AND product.status = 1;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();

                      rset.next();
                           String q = si;
                           String p = rset.getString("price");
                           temp.addElement(rset.getString("name"));
                           temp.addElement(p);
                           temp.addElement(q);

                           float x = Float.valueOf(p);
                           int y = Integer.parseInt(q);
                           float subtotal = x * y;
                           int ret = 1;
                           
                           temp.addElement(""+subtotal);
                           
                           if(ret == 1){
                               for(int i = 0; i<temp.size(); i++){
                                    row.add(temp.elementAt(i));
                               }

                               sum += subtotal;
                               jTextField2.setText(""+sum);
                               rowCount++;
                               
                           }
                         
                           
            } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }

        
      public void searchData(String type, String s)
      {
          Vector temp = new Vector();
            try {
                       DB.connect();
                       conn = DB.getConn();

                       query = "Select product.productNo, product.name, product.price from product where product."+type+" = '"+s+"' AND product.status = 1;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();

                       if(rset.next() == false){
                           checkRowCount();
                           back--;
                           JOptionPane.showMessageDialog(null, "Product does not exist or disabled", "Error",JOptionPane.WARNING_MESSAGE);
                       }
                       else{
                           String q = jTextField4.getText();
                           String p = rset.getString("price");
                           temp.addElement(rset.getString("name"));
                           temp.addElement(p);
                           temp.addElement(q);

                           String prodNo = rset.getString("productNo");
                           addItems(prodNo, q);

                           float x = Float.valueOf(p);
                           int y = Integer.parseInt(q);
                           float subtotal = x * y;
                           int ret = getQuantity(prodNo, y, 0);

                           temp.addElement(""+subtotal);

                           if(ret == 1){
                               for(int i = 0; i<temp.size(); i++){
                                    row.add(temp.elementAt(i));
                               }

                               sum += subtotal;
                               jTextField2.setText(""+sum);
                               rowCount++;
                               setValues(row, rowCount);
                           }
                       }
                    
                    DB.disconnect();
                    pstmt.close();


            } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }

       public void searchClaim(String s, String q)
      {
            try {
                       DB.connect();
                       conn = DB.getConn();

                       query = "Select product.productNo from product where product.name = '"+s+"' AND product.status = 1;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();

                       rset.next();
                       addItems(rset.getString("productNo"), q);

                    DB.disconnect();
                    pstmt.close();


            } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }

      public void addTransaction(Vector row){

            try {

            	DB.connect();
            	conn = DB.getConn();

                      query = "INSERT INTO `introse`.`transaction` (`transactionNo`, `name`, `totalAmount`, `date`, `status`) VALUES ('"+count+"', '"+row.elementAt(0)+"', '"+row.elementAt(1)+"', '"+row.elementAt(2)+"', '1');";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                 JOptionPane.showMessageDialog(null, "Transaction Successfully Added!", "Add Transaction", JOptionPane.WARNING_MESSAGE);
                 DB.disconnect();
                 pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }

      public void addItems(String s, String q){

            try {

            	DB.connect();
            	conn = DB.getConn();

                      query = "INSERT INTO `introse`.`transaction_has_items` (`transactionNo`, `productNo`, `quantity`) VALUES ('"+count+"', '"+s+"', '"+q+"');";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                 DB.disconnect();
                 pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }

      public void searchRemove(String s, int q){

       try {
                DB.connect();
            	conn = DB.getConn();

                System.out.println("Connection Successful!!");

                query = "select product.productNo from product where product.name = '"+s+"'";
                pstmt = conn.prepareStatement(query);
                rset = pstmt.executeQuery();

                rset.next();
                String prodNo = rset.getString("productNo");
                getQuantity(prodNo, q, 1);
                removeItems(prodNo);

                DB.disconnect();
                System.out.println("Disconnected!");
                pstmt.close();



             } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
             }

       }

       public void removeItems(String s){

            try {

            	DB.connect();
            	conn = DB.getConn();

                      query = "delete from transaction_has_items where productNo = '"+s+"' AND transactionNo = '"+count+"';";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                 DB.disconnect();
                 pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }

      public int getQuantity(String s, int q, int stat){
            int ret = 0;
            try {

            	DB.connect();
            	conn = DB.getConn();
                query = "select quantity from stocks where productNo = '"+s+"';";
                pstmt = conn.prepareStatement(query);
                rset = pstmt.executeQuery();

                 rset.next();
                 int stock = rset.getInt("quantity");

                 if(stock != 0 && stock >= q){
                     if(stat == 0)
                         stock -= q;
                     else
                         stock += q;
                     setQuantity(stock, s);
                     ret = 1;
                 }
                 else if(stock == 0){
                     JOptionPane.showMessageDialog(null, "No Stock Left.", "Error", JOptionPane.ERROR_MESSAGE);
                     back--;
                 }
                 else if(stock < q){
                     JOptionPane.showMessageDialog(null, " Quantity entered exceeded the stock.", "Error", JOptionPane.ERROR_MESSAGE);
                     back--;
                 }

                DB.disconnect();
                pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
            return ret;
      }

       public void setQuantity(int q, String s){

            try {

            	DB.connect();
            	conn = DB.getConn();
                
                      query = "update stocks set quantity = "+q+" where productNo = "+s+";";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                 DB.disconnect();
                 pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
      }
       
         public void setIndex(int index) {
        this.index = index;
        setAll(index);
        setItems(index);
        
    }
       
      public void setAll (int index){
          if(index == 0){
              getDatabase();
              jTextField3.setText("");
              jTextField1.setText("");
              jTextField2.setText("");
              jTextField4.setText("");
          }
          else if (index > 0){

              Vector result = new Vector();
              Vector result1 = new Vector();

              try {

            	DB.connect();
            	conn = DB.getConn();

                      query = "select * from transaction where transactionNo = "+index+"";
                      pstmt = conn.prepareStatement(query);
                      rset = pstmt.executeQuery();

                      rset.next();
                      int i = Integer.parseInt(rset.getString("transactionNo"));
                      count = i;
                      jLabel2.setText(""+i);
                      jLabel5.setText(rset.getString("date"));
                      jTextField1.setText(rset.getString("name"));
                      jTextField2.setText(rset.getString("totalAmount"));
                      
                 System.out.println("Transaction record successfully updated.");
                 DB.disconnect();
                 pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
          }
      }
      
      public void setItems (int index){
          if(index == 0){
              getDatabase();
              
          }
                  
          else if (index > 0){

              String pe[] = new String[100];
              String se = "productNo";
               String qt[] = new String[100];
             int counter=0;
               try {

            	DB.connect();
            	conn = DB.getConn();
                
                      query = "select * from transaction_has_items where transactionNo = "+index+"";
                      pstmt = conn.prepareStatement(query);
                      rset = pstmt.executeQuery();
                    
                    while(rset.next()){
                    pe[counter] = rset.getString("productNo");
                    qt[counter] = rset.getString("quantity");
                    System.out.println(pe[counter]);
                    counter++;
                        
                    }
                    for(int gege=0;gege<counter;gege++){
                        System.out.println(pe[gege]);
                    setData(se,pe[gege], qt[gege]);
                    
                    }
                    setValues(row,rowCount);
                    
                    
                 System.out.println("Transaction record successfully updated.");
               DB.disconnect();
                 pstmt.close();
                      
                    
            }
               catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
          }
      }
      
      
public void updateTransaction(String name, String date, float amt){

            try {

            	DB.connect();
            	conn = DB.getConn();

                      query = "update transaction set name = '"+name+"', date = '"+date+"', totalAmount = '"+amt+"',status =1  where transactionNo = 00000000"+count+"";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                 System.out.println("transaction record successfully updated.");
                 JOptionPane.showMessageDialog(null, "Transaction Successfully Updated!", "Add Transaction", JOptionPane.WARNING_MESSAGE);
                 DB.disconnect();
                 pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
}

    /**
     * @param typer the typer to set
     */
    public void setTyper(int typer) {
        this.typer = typer;
    }
}
